//
//  HJChatGroupManager.m
//  KaiChat
//
//  Created by lx on 2023/10/23.
//

#import "HJChatGroupManager.h"
#import "HJChatGroupModel.h"
#import "HJGroupMemberModel.h"
#import "HJIM.h"
#import "HJGroupInviteModel.h"
#import "HJChatMessageModel.h"

@implementation HJChatGroupManager

- (void)queryGroupInfoByGroupId:(NSString *)groupId completion:(void (^)(HJChatGroupModel * _Nullable groupModel))completion {
    HJChatGroupModel *groupModel = [self queryGroupInfoByGroupId:groupId];
    if (groupModel) {
        completion(groupModel);
    } else {
        //首次加载群信息,查询全部群成员
        [HJIM.shareIM.groupManager loadGroupMemberListWithGroupId:groupId completion:^(NSArray<HJChatUserModel *> * _Nullable datas) {}];
        [self loadGroupInfoByGroupId:groupId completion:completion];
    }
}

- (HJChatGroupModel *)queryGroupInfoByGroupId:(NSString *)groupId {
    NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"groupId"),bg_sqlValue(groupId)];
    return [HJChatGroupModel bg_find:[HJChatGroupModel bg_tableName] where:where].lastObject;
}

- (void)createGroupWithUserIds:(NSArray *)userIds completion:(void (^)(HJChatGroupModel * _Nullable groupModel, NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_createGroup parameters:@{
        @"user_ids": userIds,
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        HJChatGroupModel *groupModel = [HJChatGroupModel modelWithBlock:^(HJChatGroupModel * _Nonnull model) {
            model.role = @1;
            model.name = data[@"name"];
            model.memberNums = data[@"nums"];
            model.avatar = data[@"avatar"];
            model.groupId = toString(data[@"room_id"]);
        }];
        [groupModel bg_saveOrUpdateAsync:nil];
        [self loadGroupMemberListWithGroupId:groupModel.groupId completion:^(NSArray<HJChatUserModel *> * _Nullable datas) {}];
        !completion ?: completion(groupModel, nil);
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil, error);
    }];
}

- (void)loadGroupInfoByGroupId:(NSString *)groupId completion:(void (^)(HJChatGroupModel * _Nullable groupModel))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_groupInfo parameters:@{
        @"room_id": @(groupId.integerValue),
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        HJChatGroupModel *model = [HJChatGroupModel groupModelWithDict:data];
        model.groupId = groupId;
        [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            
            if (model.role == 0 || model.status.intValue == 2 || model.userStatus != 1) {
                [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"), bg_sqlValue(HJUserInfo.userId)] complete:^(BOOL isSuccess) {}];
            }
            
            dispatch_async_main_queue(^{
                !completion ?: completion(model);
            });
        }];
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}

- (void)queryGroupListWithCompletion:(void (^)(NSArray <NSArray <HJChatGroupModel *>*>* _Nullable datas))completion {
    
    dispatch_async_sql_queue(^{
       
        NSArray *createDatas = [HJChatGroupModel bg_find:[HJChatGroupModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"role"),bg_sqlValue(@"1")]];
        NSArray *joinDatas = [HJChatGroupModel bg_find:[HJChatGroupModel bg_tableName] where:[NSString stringWithFormat:@"where %@!=%@", bg_sqlKey(@"role"),bg_sqlValue(@"1")]];
        
        if (createDatas.count || joinDatas.count) {
            dispatch_async_main_queue(^{
                !completion ?: completion(@[createDatas, joinDatas]);
            });
        }
    });
}

- (void)loadGroupListWithCompletion:(void (^)(NSArray <NSArray <HJChatGroupModel *>*>* _Nullable datas))completion {
    
    [self queryGroupListWithCompletion:completion];
 
    [HJNetworking.shareNetwork POSTBodyJSON:API_groupList parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        dispatch_async_sql_queue(^{
            
            NSArray *create_room = data[@"create_room"];
            NSArray *join_room = data[@"join_room"];
            
            NSMutableArray *datas = [NSMutableArray array];
            if ([create_room isKindOfClass:NSArray.class]) {
                [datas addObjectsFromArray:create_room];
            }
            if ([join_room isKindOfClass:NSArray.class]) {
                [datas addObjectsFromArray:join_room];
            }
            
            NSMutableArray *allDatas = [NSMutableArray array];
            NSMutableArray *groupIds = [NSMutableArray array];
            
            for (NSDictionary *dict in datas) {
                [HJChatGroupModel modelWithBlock:^(HJChatGroupModel * _Nonnull model) {
                    model.role = dict[@"role"];
                    model.groupId = toString(dict[@"room_id"]);
                    model.memberNums = dict[@"nums"];
                    model.avatar = dict[@"avatar"];
                    model.name = dict[@"name"];
                    model.intro = dict[@"intro"];
                    
                    if (!isEmptyString(model.groupId)) {
                        [groupIds addObject:model.groupId];
                        [allDatas addObject:model];
                    }
                }];
            }
            
            NSArray *models = [HJChatGroupModel bg_findAll:[HJChatGroupModel bg_tableName]];
            for (HJChatGroupModel *  _Nonnull obj in models) {
                if (![groupIds containsObject:obj.groupId]) {
                    if (isEmptyString(obj.groupId)) {
                        [HJChatGroupModel bg_delete:[HJChatGroupModel bg_tableName] where:[NSString stringWithFormat:@"where %@ is null", bg_sqlKey(@"groupId")]];
                    } else {
                        [HJChatGroupModel bg_delete:[HJChatGroupModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"groupId"),bg_sqlValue(obj.groupId)]];
                    }
                }
            }
            [HJChatGroupModel bg_saveOrUpdateArray:allDatas];
            
                NSArray *createDatas = [HJChatGroupModel bg_find:[HJChatGroupModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"role"),bg_sqlValue(@"1")]];
                NSArray *joinDatas = [HJChatGroupModel bg_find:[HJChatGroupModel bg_tableName] where:[NSString stringWithFormat:@"where %@!=%@", bg_sqlKey(@"role"),bg_sqlValue(@"1")]];
         
            dispatch_async_main_queue(^{
                !completion ?: completion(@[createDatas, joinDatas]);
            });          
        });
        
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}

- (void)openGroupInviteVerifyWithGroupId:(NSString *)groupId open:(BOOL)open completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_groupInvite parameters:@{
        @"room_id": @(groupId.integerValue),
        @"op": open ? @"open" : @"close"
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        !completion ?: completion(nil);
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
    
}

- (void)queryGroupMemberListWithGroupId:(NSString *)groupId completion:(void (^)(NSArray <HJGroupMemberModel *>* _Nullable datas))completion {
    [HJGroupMemberModel bg_findAsync:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:nil complete:^(NSArray * _Nullable array) {
        !completion ?: completion(array);
    }];
}

- (NSArray *)groupMemberModelsSort:(NSArray *)datas {
    
    if (datas.count == 0) return datas;
    
    HJGroupMemberModel *ownerModel = nil;
    for (HJGroupMemberModel *obj in datas) {
        if (obj.role == 1) {
            ownerModel = obj;
            break;
        }
    }
    
    if (!ownerModel) return datas;
    
    NSMutableArray *memberModels = [NSMutableArray arrayWithArray:datas];
    [memberModels removeObject:ownerModel];
 
    NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
    for (HJGroupMemberModel *obj in memberModels) {
 
        NSString *displayName = obj.nickname;
        NSString *firstLetter = [displayName.firstPinYin uppercaseString];
        if (firstLetter.length == 0 || !isalpha([firstLetter characterAtIndex:0])) {
            firstLetter = @"#";
        }
        NSMutableArray *dictMarr = [mainDict valueForKey:firstLetter];
        if (!dictMarr) {
            [mainDict setValue:[NSMutableArray array] forKey:firstLetter];
            dictMarr = [mainDict valueForKey:firstLetter];
        }
        [dictMarr addObject:obj];
    }
    NSArray *nonameList = [mainDict valueForKey:@"#"];
    if (nonameList) {
        [mainDict removeObjectForKey:@"#"];
    }
    
    NSArray *sortKeys = [mainDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull obj1, NSString *  _Nonnull obj2) {
        return [obj1 compare:obj2] == NSOrderedDescending;
    }];
 
    [memberModels removeAllObjects];
    [sortKeys enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [memberModels addObjectsFromArray:mainDict[obj]];
    }];
    
    if (nonameList.count) {
        [memberModels addObjectsFromArray:nonameList];
    }
    
    [memberModels insertObject:ownerModel atIndex:0];
    return memberModels;
}

//- (NSArray *)groupMemberModelsSort:(NSArray *)datas {
//
//    if (datas.count == 0) return datas;
//
//    HJGroupMemberModel *ownerModel = nil;
//    for (HJGroupMemberModel *obj in datas) {
//        if (obj.role == 1) {
//            ownerModel = obj;
//            break;
//        }
//    }
//
//    if (!ownerModel) return datas;
//    NSMutableArray *memberModels = [NSMutableArray arrayWithArray:datas];
//    [memberModels removeObject:ownerModel];
//
//    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"nickname" ascending:YES];
//    NSArray *sortedModels = [memberModels sortedArrayUsingDescriptors:@[sortDescriptor]];
//    [memberModels removeAllObjects];
//    [memberModels addObjectsFromArray:sortedModels];
//    [memberModels insertObject:ownerModel atIndex:0];
//    return memberModels;
//}

- (NSArray *)queryGroupMemberListWithGroupId:(NSString *)groupId {
    return [HJGroupMemberModel bg_find:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:nil];
}

- (void)loadGroupMemberListWithGroupId:(NSString *)groupId completion:(void (^)(NSArray <HJGroupMemberModel *>* _Nullable datas))completion {
    [HJNetworking.shareNetwork GET:API_groupMemberList parameters:@{
        @"room_id": @(groupId.integerValue),
        @"type": @2
    } success:^(NSDictionary * _Nonnull responseObject, NSArray *  _Nonnull data) {
        
        NSMutableArray *datas = [NSMutableArray arrayWithCapacity:data.count];
        for (NSDictionary *dict in data) {
            HJGroupMemberModel *model = [HJGroupMemberModel modelWithDict:dict];
            model.groupId = groupId;
            [datas addObject:model];
        }
        !completion ?: completion(datas);
        
        [HJGroupMemberModel bg_clearAsync:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] complete:^(BOOL isSuccess) {
            [HJGroupMemberModel bg_saveOrUpdateArray:datas];
        }];
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}


- (void)editGroupInfoByGroupId:(NSString *)groupId avatar:(NSString *)avatar name:(NSString *)name intro:(nullable NSString *)intro completion:(void (^)(HJChatGroupModel * _Nullable groupModel))completion {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@(groupId.integerValue) forKey:@"room_id"];
    [parameters setValue:avatar forKey:@"avatar"];
    [parameters setValue:intro forKey:@"intro"];
    [parameters setValue:name forKey:@"name"];
    
    [HJNetworking.shareNetwork POSTBodyJSON:API_modifyGroupInfo parameters:parameters success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        dispatch_async_sql_queue(^{
            HJChatGroupModel *groupModel = [self queryGroupInfoByGroupId:groupId];
            groupModel.name = name;
            groupModel.avatar = avatar;
            if (!isEmptyString(intro)) {
                groupModel.intro = intro;
            }
            [groupModel bg_saveOrUpdate];
            
            dispatch_async_main_queue(^{
                !completion ?: completion(groupModel);
            });
        });
        
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
}


- (void)searchGroupByKeyword:(NSString *)keyword completion:(void (^)(NSArray <HJChatGroupModel *> * _Nullable datas))completion {
    NSString * where = [NSString stringWithFormat:@"where (%@ like '%%%@%%') ",bg_sqlKey(@"name"),keyword];
    [HJChatGroupModel bg_findAsync:[HJChatGroupModel bg_tableName] where:where complete:^(NSArray * _Nullable array) {
        !completion ?: completion(array);
    }];
}

- (void)postGroupNoticeByGroupId:(NSString *)groupId content:(NSString *)content completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_postNotice parameters:@{
        @"room_id": @(groupId.integerValue),
        @"content": content
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        !completion ?: completion(nil);
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}

- (void)loadGroupNoticeDetailByGroupId:(NSString *)groupId completion:(void (^)(NSDictionary * _Nullable data))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_noticeDetail parameters:@{
        @"room_id": @(groupId.integerValue),
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        if (![data isKindOfClass:NSDictionary.class]) {
            !completion ?: completion(nil);
            return;
        }

        dispatch_async_sql_queue(^{
            HJChatGroupModel *groupModel = [self queryGroupInfoByGroupId:groupId];
            
            NSMutableDictionary *groupNoticeInfo = [NSMutableDictionary dictionaryWithDictionary:data];
            [groupNoticeInfo removeObjectForKey:@"content"];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            NSDictionary *extensionDict = groupModel.extension.mj_JSONObject;
            [dict addEntriesFromDictionary:extensionDict];
            
            [dict setValue:groupNoticeInfo forKey:groupNoticeInfoKey];
          
            groupModel.extension = dict.mj_JSONString;
            groupModel.showNotice = @(2);
            [groupModel bg_saveOrUpdate];
            
            dispatch_async_main_queue(^{
                !completion ?: completion(data);
            });
        });
        
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}

- (void)inviteFridendJoinGroupByGroupId:(NSString *)groupId userModels:(NSArray *)userModels completion:(void (^)(NSError * _Nullable error))completion {
    
    dispatch_async_sql_queue(^{
        
        NSMutableArray *userIds = [NSMutableArray array];
        for (HJChatFriendModel *model in userModels) {
            [userIds addObject:model.userId];
        }
        
        NSInteger max_seq_id = [HJIM.shareIM.messageManager getMaxServerMsgIdMessagesBySessionId:groupId].integerValue;
        [HJNetworking.shareNetwork POSTBodyJSON:API_inviteMembers parameters:@{
            @"room_id": @(groupId.integerValue),
            @"user_ids": userIds,
            @"max_seq_id": @(max_seq_id)
        } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
            
            NSMutableArray *datas = [NSMutableArray array];
            [userModels enumerateObjectsUsingBlock:^(HJChatFriendModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                HJGroupMemberModel *groupMemberModel = [HJGroupMemberModel modelWithFridendModel:obj];
                groupMemberModel.groupId = groupId;
                [datas addObject:groupMemberModel];
            }];
            
            [HJGroupMemberModel bg_saveOrUpdateArrayAsync:datas complete:^(BOOL isSuccess) {
                dispatch_async_main_queue(^{
                    !completion ?: completion(nil);
                });
            }];
        } failure:^(NSError * _Nonnull error) {
            !completion ?: completion(error);
        }];
    });
    
}

- (void)inviteFridendJoinGroupByGroupId:(NSString *)groupId userIds:(NSArray *)userIds completion:(void (^)(NSError * _Nullable error))completion {
    
    dispatch_async_sql_queue(^{
   
        NSInteger max_seq_id = [HJIM.shareIM.messageManager getMaxServerMsgIdMessagesBySessionId:groupId].integerValue;
        [HJNetworking.shareNetwork POSTBodyJSON:API_inviteMembers parameters:@{
            @"room_id": @(groupId.integerValue),
            @"user_ids": userIds,
            @"max_seq_id": @(max_seq_id)
        } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
            !completion ?: completion(nil);
        } failure:^(NSError * _Nonnull error) {
            !completion ?: completion(error);
        }];
    });
}

- (void)removeGroupMemberByGroupId:(NSString *)groupId userIds:(NSArray *)userIds completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_removeMembers parameters:@{
        @"room_id": @(groupId.integerValue),
        @"user_ids": userIds,
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        dispatch_async_sql_queue(^{
            for (NSString *userId in userIds) {
                [HJGroupMemberModel bg_delete:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"), bg_sqlValue(userId)]];
            }
            dispatch_async_main_queue(^{
                !completion ?: completion(nil);
            });
        });
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}

- (void)addGroupManagerByGroupId:(NSString *)groupId userIds:(NSArray *)userIds completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_addGroupManager parameters:@{
        @"room_id": @(groupId.integerValue),
        @"user_ids": userIds,
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        dispatch_async_sql_queue(^{
            for (NSString *userId in userIds) {
                NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(userId)];
                HJGroupMemberModel *groupMemberModel = [HJGroupMemberModel bg_find:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:where].lastObject;
                groupMemberModel.role = 2;
                [groupMemberModel bg_saveOrUpdate];
            }
            
            dispatch_async_main_queue(^{
                !completion ?: completion(nil);
            });
        });
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}

- (void)removeGroupManagerByGroupId:(NSString *)groupId userIds:(NSArray *)userIds completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_removeGroupManager parameters:@{
        @"room_id": @(groupId.integerValue),
        @"user_ids": userIds,
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        dispatch_async_sql_queue(^{
            for (NSString *userId in userIds) {
                NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(userId)];
                HJGroupMemberModel *groupMemberModel = [HJGroupMemberModel bg_find:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:where].lastObject;
                groupMemberModel.role = 3;
                [groupMemberModel bg_saveOrUpdate];
            }
            
            dispatch_async_main_queue(^{
                !completion ?: completion(nil);
            });
        });
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}

- (void)exitGroupByGroupId:(NSString *)groupId completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_exitGroup parameters:@{
        @"room_id": @(groupId.integerValue),
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        //从群成员中删除
        [HJIM.shareIM.conversationManager deleteConversationWithSessionId:groupId completion:^(NSError * _Nonnull error) {
            dispatch_async_main_queue(^{
                !completion ?: completion(nil);
            });
        }];
        [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:nil complete:^(BOOL isSuccess) {}];
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}

- (void)disbandGroupByGroupId:(NSString *)groupId completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_disbandGroup parameters:@{
        @"room_id": @(groupId.integerValue),
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        [HJIM.shareIM.conversationManager deleteConversationWithSessionId:groupId completion:^(NSError * _Nonnull error) {
            dispatch_async_main_queue(^{
                !completion ?: completion(nil);
            });
        }];
        [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:nil complete:^(BOOL isSuccess) {}];
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}

- (void)transferGroupByGroupId:(NSString *)groupId userId:(NSString *)userId completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_transferGroup parameters:@{
        @"room_id": @(groupId.integerValue),
        @"user_id": userId
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        !completion ?: completion(nil);
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}


- (void)loadGroupInviteListWithGroupId:(NSString *)groupId completion:(void (^)(NSArray <HJGroupInviteModel *>* _Nullable datas))completion {
    [HJNetworking.shareNetwork GET:API_groupInviteList parameters:@{
        @"room_id": @(groupId.integerValue),
        @"page": @1,
        @"size": @498
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        NSMutableArray *datas = [NSMutableArray array];
        for (NSDictionary *dict in data) {
            HJGroupInviteModel *groupInviteModel = [HJGroupInviteModel modelWithDict:dict];
            groupInviteModel.groupId = groupId;
            [datas addObject:groupInviteModel];
        }
        
        !completion ?: completion(datas);
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
}

- (void)loadGroupInviteCountWithGroupId:(NSString *)groupId complete:(void (^__nullable)(NSInteger count))complete {
    [HJNetworking.shareNetwork GET:API_groupInviteCount parameters:@{
        @"room_id": @(groupId.integerValue),
        @"type": @1,
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        NSInteger num =  [data[@"nums"] intValue];
        
        dispatch_async_sql_queue(^{
            HJChatGroupModel *groupModel = [self queryGroupInfoByGroupId:groupId];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            NSDictionary *extensionDict = groupModel.extension.mj_JSONObject;
            [dict addEntriesFromDictionary:extensionDict];
            
            [dict setValue:@(num) forKey:groupInviteCountKey];
            groupModel.extension = dict.mj_JSONString;
            [groupModel bg_saveOrUpdate];
        });
        !complete ?: complete(num);
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(0);
    }];
    
}

- (void)agreeUserJoinGroupByGroupId:(NSString *)groupId userIds:(NSArray *)userIds completion:(void (^)(NSError * _Nullable error))completion {
    dispatch_async_sql_queue(^{
        NSInteger max_seq_id = [HJIM.shareIM.messageManager getMaxServerMsgIdMessagesBySessionId:groupId].integerValue;
        [HJNetworking.shareNetwork POSTBodyJSON:API_agreeGroupInvite parameters:@{
            @"room_id": @(groupId.integerValue),
            @"user_ids": userIds,
            @"max_seq_id": @(max_seq_id)
        } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
            !completion ?: completion(nil);
        } failure:^(NSError * _Nonnull error) {
            !completion ?: completion(error);
        }];
    });
}

//获取群的最新一条群公告
- (HJChatMessageModel *)queryGroupLastNoticeByGroupId:(NSString *)groupId {
    NSString * where = [NSString stringWithFormat:@"where %@=%@ or %@=%@ ORDER BY %@ desc limit 1",bg_sqlKey(@"messageType"), bg_sqlValue(@(HJMessageTypeNotice)), bg_sqlKey(@"systemMsgType"), bg_sqlValue(@(HJChatSystemMsgTypePostGroupNotice)), bg_sqlKey(@"timestamp")];
    return [HJChatMessageModel bg_find:[HJChatMessageModel bg_tableNameWithSessionId:groupId] where:where].lastObject;
}

- (void)loadPublicGroupInfoByGroupId:(NSString *)groupId completion:(void (^)(HJChatGroupModel * _Nullable groupModel, NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork GET:API_publicGroupInfo parameters:@{
        @"room_id": @(groupId.integerValue),
        @"user_id": HJUserInfo.userId
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        HJChatGroupModel *model = [HJChatGroupModel groupModelWithDict:data];
        model.groupId = groupId;
        [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            if (model.role == 0 || model.status.intValue == 2 || model.userStatus != 1) {
                [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"), bg_sqlValue(HJUserInfo.userId)] complete:^(BOOL isSuccess) {}];
            }
            dispatch_async_main_queue(^{
                !completion ?: completion(model, nil);
            });
        }];
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil, error);
    }];
}

- (void)joinGroupInfoByGroupId:(NSString *)groupId completion:(void (^)(NSError * _Nullable error))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_joinGroup parameters:@{
        @"room_id": @(groupId.integerValue),
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        !completion ?: completion(nil);
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(error);
    }];
}

@end
